// ignore_for_file: prefer_const_constructors, avoid_print

import 'dart:async';

import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:junyeyishu/ui/login/QGVerifyAliPage.dart';

import 'package:junyeyishu/utils/utils.dart';
import 'package:junyeyishu/widgets/QGWidget.dart';

class QGModifyTradePasswordPage extends StatefulWidget {
  const QGModifyTradePasswordPage({super.key});

  @override
  State<QGModifyTradePasswordPage> createState() =>
      _QGModifyTradePasswordPageState();
}

class _QGModifyTradePasswordPageState extends State<QGModifyTradePasswordPage> {
  final passwordController = TextEditingController();
  final confirmPasswordController = TextEditingController();
  final codeController = TextEditingController();

  bool isInput = false;

  String? sign;
  Timer? timer;
  int countdown = 0;

  @override
  void dispose() {
    timer?.cancel();
    passwordController.dispose();
    confirmPasswordController.dispose();
    codeController.dispose();

    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return QGScaffold(
        bgColor: Color(0xFF0C1012),
        title: '',
        body: GestureDetector(
          onTap: () {
            unfocus(context);
          },
          child: Container(
              padding: EdgeInsets.only(left: 15.rpx, right: 15.rpx),
              child: Column(children: [
                SizedBox(height: 14.rpx),
                buildPassword(passwordController, '设置新密码'),
                SizedBox(height: 15.rpx),
                buildPassword(confirmPasswordController, '再次输入密码'),
                SizedBox(height: 15.rpx),
                buildCode(codeController, '请输入验证码'),
                SizedBox(height: 20.rpx),
                buildTip(),
                SizedBox(height: 30.rpx),
                buildButton(),
              ])),
        ));
  }

  buildPassword(controller, text) {
    return Container(
        alignment: Alignment.centerLeft,
        height: 52.rpx,
        padding: EdgeInsets.fromLTRB(22.rpx, 15.rpx, 22.rpx, 15.rpx),
        decoration: BoxDecoration(
          border: Border(
            bottom: BorderSide(
              color: Color(0XFF3D4854)
            )
          ),
            color: Color(0xFF0C1012)),
        child: TextField(
          controller: controller,
          keyboardType: TextInputType.number,
          cursorColor: Color(0xFFFFFFFF),
          obscureText: true,
          obscuringCharacter: '*',
          inputFormatters: [LengthLimitingTextInputFormatter(6)],
          style: TextStyle(
            fontSize: 13.rpx,
            fontWeight: FontWeight.normal,
            color: Color(0xFFFFFFFF),
            textBaseline: TextBaseline.alphabetic,
          ),
          onChanged: ((value) {
            checkPassword(value);
          }),
          decoration: InputDecoration(
              hintText: text,
              hintStyle: TextStyle(color: Color(0xFF999999)),
              isCollapsed: true,
              border: OutlineInputBorder(borderSide: BorderSide.none),
              enabledBorder: InputBorder.none,
              focusedBorder: InputBorder.none),
        ));
  }

  buildCode(controller, text) {
    return Stack(
      children: [
        Container(

            height: 52.rpx,
            padding: EdgeInsets.fromLTRB(22.rpx, 15.rpx, 22.rpx, 15.rpx),
            decoration: BoxDecoration(
               border: Border(
            bottom: BorderSide(
              color: Color(0XFF3D4854)
            )
          ),
                color: Color(0xFF0C1012)),
            child: Row(
              children: [
                Expanded(
                  child: TextField(
                    controller: controller,
                    keyboardType: TextInputType.number,
                    cursorColor: Color(0xFFFFFFFF),
                    style: TextStyle(
                      fontSize: 13.rpx,
                      fontWeight: FontWeight.normal,
                      color: Color(0xFFFFFFFF),
                      textBaseline: TextBaseline.alphabetic,
                    ),
                    onChanged: ((value) {
                      checkPassword(value);
                    }),
                    decoration: InputDecoration(
                        hintText: text,
                        hintStyle: TextStyle(color: Color(0xFF999999)),
                        isCollapsed: true,
                        border: OutlineInputBorder(borderSide: BorderSide.none),
                        enabledBorder: InputBorder.none,
                        focusedBorder: InputBorder.none),
                  ),
                ),
              ],
            )),
        Positioned(
          top: 0,
          bottom: 0,
          right: 10.rpx,
          child: TextButton(
            onPressed: () {
              toVerify();
            },
            child: Text(
              countdown > 0 ? "$countdown秒重新发送" : "发送验证码",
              style: TextStyle(
                  color: Color(0xFFFFFFFF),
                  fontSize: 13.rpx,
                  fontWeight: FontWeight.normal),
            ),
          ),
        ),
      ],
    );
  }

  buildTip() {
    return Container(
      alignment: Alignment.center,
      child: Text(
        '',
        style: TextStyle(
            fontSize: 11.rpx,
            fontWeight: FontWeight.normal,
            color: Color(0xFF999999)),
      ),
    );
  }

  buildButton() {
    return Row(
      children: [
        Expanded(
            child: Container(
          height: 44.rpx,
          decoration: isInput
              ? BoxDecoration(
                  gradient: const LinearGradient(
                    begin: Alignment.centerLeft,
                    end: Alignment.centerRight,
                    colors: [Color(0xFF4AE3FF), Color(0xFF44FFF0)],
                  ),
                  borderRadius: BorderRadius.circular(19.rpx),
                )
              : BoxDecoration(
                  gradient: LinearGradient(
                    begin: Alignment.centerLeft,
                    end: Alignment.centerRight,
                    colors: [
                      const Color(0xFF4AE3FF).withOpacity(0.4),
                      const Color(0xFF44FFF0).withOpacity(0.4)
                    ],
                  ),
                  borderRadius: BorderRadius.circular(19.rpx),
                ),
          child: TextButton(
            onPressed: toSetPassward,
            child: Text(
              '确认',
              style: TextStyle(
                  fontSize: 14.rpx,
                  fontWeight: FontWeight.bold,
                  color: isInput ? Color(0xFF111111) : Color(0xFF999999)),
            ),
          ),
        ))
      ],
    );
  }

  start() {
    countdown = 60;
    setState(() {});
    timer = Timer.periodic(Duration(seconds: 1), (timer) {
      countdown--;
      if (countdown == 0) {
        timer.cancel();
      }
      if (mounted) {
        setState(() {});
      }
    });
  }

  toVerify() {
    if (countdown > 0) {
      return;
    }

    unfocus(context);

    if (passwordController.text.length != 6 ||
        passwordController.text != confirmPasswordController.text) {
      toast("请正确设置交易密码");
      return;
    }

    showDialog(
        context: context,
        builder: (context) {
          return QGVerifyAliPage(phone: User.current?.phone ?? "");
        }).then((value) {
      if (value is! Map) return;
      sign = value["sign"];
      start();
    });

    //  var param = {};

    // param["captchaVerifyParam"] = '';
    // param["phone"] =User.current?.phone ?? "";
    // Map<String, dynamic> stringMap = param.cast<String, dynamic>();

    // Network.post(url_captchaToSms, data: stringMap).then((res) {
    //   if (!res.success) {
    //     toast(res.msg);
    //     Future.delayed(Duration(seconds: 1), () {
    //       Navigator.of(context).pop();
    //     });
    //     return;
    //   } else {
    //     toast(res.data["msg"]);
    //   }

    //   param["sign"] = res.data["sign"];

    //   Future.delayed(Duration(seconds: 1), () {
    //     Navigator.of(context).pop(param);
    //   });
    // });
  


  }

  checkPassword(value) {
    var password = passwordController.text;
    var confoirmPassword = confirmPasswordController.text;
    var code = codeController.text;

    if (password.isNotEmpty && confoirmPassword.isNotEmpty && code.isNotEmpty) {
      isInput = true;
      setState(() {});
    } else {
      isInput = false;
      setState(() {});
    }
  }

  toSetPassward() {
    unfocus(context);

    var password = passwordController.text;
    var confoirmPassword = confirmPasswordController.text;
    var code = codeController.text;

    if (isInput == false) {
      return;
    }

    if (password.isEmpty || password.length != 6) {
      toast('请输入密码');
      return;
    }

    if (confoirmPassword.isEmpty || confoirmPassword.length != 6) {
      toast('请再次输入密码');
      return;
    }

    if (password != confoirmPassword) {
      toast('两次密码不一致，请重新输入');
      return;
    }

    // var param = {};
    // param["password"] = password;
    // param["code"] = code;
    // param["sign"] = sign;

 final data = FormData.fromMap({
      "code":code,
      "password":password,
      "sign":sign
     });

    Network.post(url_u_modifyDealPassword, data: data).then((res) {
      toast(res.msg);
      if (!res.success) return;

      Future.delayed(const Duration(seconds: 2));
      Navigator.of(context).pop();
    });
  }
}
